﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using ESOL.Business.Mst;
using ESOL.Business.Pur;
using ESOL.Common;
using ESOL.Common.Entity;
using ESOL.WinUI.MasterData;
using System.IO;
using ESOL.WinUI.Hr;
using ESOL.WinUI.Bpt;

namespace ESOL.WinUI.Pur
{
    public partial class frmManagePurchasePlan : BaseForm.frmBaseMdiBusinessForm
    {
        #region Variable
        private PurApplicationItemEntity mSelectedApplicationItem;
        #endregion

        #region Constructor
        public frmManagePurchasePlan()
        {
            InitializeComponent();
        }
        #endregion

        #region Functions
        private void BindComboBox()
        {
            UICommon.UICommonFunctions.BindGridComboboxByEnum(colIS_PRODUCT_PURCHASE, typeof(PurchaseCategory), typeof(int), false);
            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(colUNIT, "UNIT", true);
        }

        private string GetCondition()
        {
            string condition = "";
            if (string.IsNullOrEmpty(txtApplicationCode.Text) == false)
            {
                condition += " AND PA.APPLICATION_CODE LIKE '%" + txtApplicationCode.Text + "%'";
            }
            if (dtpRequiredDeliveryDate.EditValue!=null)
            {
                condition += " AND PAI.DELIVERY_REQUIRED_DATE >= CONVERT(DATETIME,'" + ((DateTime)dtpRequiredDeliveryDate.EditValue).ToString("yyyy-MM-dd") + "')";
            }
            if (dtpRequiredDeliveryDateTo.EditValue!=null)
            {
                condition += " AND PAI.DELIVERY_REQUIRED_DATE <= CONVERT(DATETIME,'" + ((DateTime)dtpRequiredDeliveryDateTo.EditValue).ToString("yyyy-MM-dd") + "')";
            }
            if (txtApplicationPerson.Tag != null && txtApplicationPerson.Tag.GetType() == typeof(MstPersonEntity))
            {
                MstPersonEntity entity = (MstPersonEntity)txtApplicationPerson.Tag;
                condition += " AND PA.APPLICATION_PERSON = '" + entity.PersonId + "' ";
            }
            if (string.IsNullOrEmpty(cmbIsProductPurchase.Text) == false && cmbIsProductPurchase.SelectedValue != null)
            {
                condition += " AND PA.IS_PRODUCT_PURCHASE = '" + cmbIsProductPurchase.SelectedValue.ToString() + "'";
            }
            if (txtProduct.Tag != null && txtProduct.Tag.GetType() == typeof(MstProductEntity))
            {
                MstProductEntity entity = (MstProductEntity)txtProduct.Tag;
                condition += " AND MP.PRODUCT_ID = '" + entity.ProductId + "' ";
            }
            if (cboxShowNonPurchased.Checked)
            {
                condition += " AND D.APPLICATION_ITEM_ID IS NULL ";
            }
            return condition;
        }

        private void BindDataGrid()
        {
            string condition = GetCondition();
            string rowCount = txtRowCount.Text;
            string orderBy = "PA.CREATED_DATE DESC, MPT.PRODUCT_TYPE_NAME";
            DataTable dt = ESOL.Business.Pur.PurApplicationItemBs.GetByCondition(condition, orderBy, rowCount);
            DataColumn dc = new DataColumn("IS_SELECTED",typeof(bool));
            dc.DefaultValue = false;
            dt.Columns.Add(dc);
            gvMain.DataSource = dt;
        }

        private void ShowPictures(string ProductCode)
        {
            try
            {
                Directory.Delete("C:" + @"\" + "TempPictures", true);
            }
            catch
            { }
            Directory.CreateDirectory("C:" + @"\" + "TempPictures");

            EsolWevServices.EsolService EService = new EsolWevServices.EsolService();
            byte[] bytes = EService.DownloadFile(ProductCode + ".jpg");
            if (bytes != null)
            {
                Image img = CommonFunctions.byteArrayToImage(bytes);
                string ssrt = "C:" + @"\" + "TempPictures" + @"\" + ProductCode + ".jpg";
                img.Save(ssrt);
                //System.Diagnostics.Process.Start("rundll32.exe shimgvw.dll,ImageView_Fullscreen" + ssrt);
                System.Diagnostics.Process process = new System.Diagnostics.Process();
                string fileName = ssrt;
                process.StartInfo.FileName = fileName;
                process.StartInfo.Arguments = "rundll32.exe C:\\WINDOWS\\system32\\shimgvw.dll,ImageView_Fullscreen";
                process.StartInfo.UseShellExecute = true;
                process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                process.Start();
                process.Close();
            }
            else
            {
                MessageBox.Show("没有与其对应的图片，请先上传图纸后查看。");
            }
        }
        #endregion

        #region Event
        protected override void OnShown(EventArgs e)
        {
            BindComboBox();
            BindDataGrid();
            base.OnShown(e);
        }

        private void txtApplicationPerson_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainEmployeeQuery frm = new frmMaintainEmployeeQuery(true);
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedPerson != null)
            {
                txtApplicationPerson.Text = frm.SelectedPerson.NameCn;
                txtApplicationPerson.Tag = frm.SelectedPerson;
            }
            else
            {
                txtApplicationPerson.Text = "";
                txtApplicationPerson.Tag = null;
            }
        }

        private void txtProduct_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainProductQuery frm = new frmMaintainProductQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedProduct != null)
            {
                txtProduct.Text = frm.SelectedProduct.ProductName;
                txtProduct.Tag = frm.SelectedProduct;
            }
            else
            {
                txtProduct.Text = "";
                txtProduct.Tag = null;
            }
        }

        protected override void Click_Query()
        {
            BindDataGrid();
        }

        protected override void Click_View()
        {
            if (mSelectedApplicationItem == null)
            {
                MessageBox.Show("请选择一个采购申请单明细！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            PurApplicationEntity app = PurApplicationBs.GetPurApplicationByID(mSelectedApplicationItem.ApplicationId);
            frmMaintainPurchaseApplication frm = new frmMaintainPurchaseApplication();
            frm.ThisActionType = ActionType.View;
            frm.SelectedPurApplication = app;
            frm.ShowDialog();
        }

        //下单
        protected override void Click_New()
        {
            if (gvMain.DataSource == null)
            {
                return;
            }
            DataTable dt=gvMain.DataSource as  DataTable;
            List<PurApplicationItemEntity> list = new List<PurApplicationItemEntity>();
            foreach (DataRow dr in dt.Rows)
            {
                if ((bool)dr["IS_SELECTED"])
                {
                    PurApplicationItemEntity m = new PurApplicationItemEntity(dr);
                    list.Add(m);
                }
            }
            if (list.Count == 0)
            {
                MessageBox.Show("请至少选择一个采购申请单明细！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            frmMaintainPurchaseOrder frm = new frmMaintainPurchaseOrder(list, null);
            frm.ThisActionType = ActionType.New;
            if (frm.ShowDialog() == DialogResult.OK)
            {
                BindDataGrid();
            }
        }

        //查看图纸
        protected override void Click_Modify()
        {
            if (mSelectedApplicationItem == null)
            {
                MessageBox.Show("请先选择一行计划");
            }
            MstProductEntity entity = new MstProductEntity();
            entity = MstProductBs.GetMstProductTypeByID(mSelectedApplicationItem.ProductId);
            ShowPictures(entity.ProductCode);
        }

        protected override void Click_Export()
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "Excel 文件(*.xls)|*.xls|Excel 文件(*.xlsx)|*.xlsx|所有文件(*.*)|*.*";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                gridView1.ExportToXls(sfd.FileName);
            }
        }

        DataRow drSelected;
        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            drSelected = gridView1.GetDataRow(e.FocusedRowHandle);
            mSelectedApplicationItem = new PurApplicationItemEntity(drSelected);
        }

        private void repositoryItemCheckEdit1_Click(object sender, EventArgs e)
        {
            if ((bool)drSelected["IS_SELECTED"])
            {
                drSelected["IS_SELECTED"] = false;
            }
            else
            {
                drSelected["IS_SELECTED"] = true;
            }
        }

        #endregion
    }
}
